import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:url_launcher/url_launcher.dart';

import '../data_model/version_info.dart';
import '../utils/log_utils.dart';
import '../utils/num_format_utils.dart';
import '../utils/toast_utils.dart';

typedef CallBack = void Function();

class UpdateDialog {
  UpdateDialog(this.data);

  VersionInfo data;
  int? id;
  String hintText = "立即更新";
  double percent = 0.0;
  String percentStr = "0.0%";
  String netInfo = "本次更新0MB，速度0kb/s";

  bool isUpdating = false;

  Future<void> androidUpgrade({required CallBack callBack}) async {
    try {
      id = await RUpgrade.upgrade(data.apkUrl,
          isAutoRequestInstall: true, useDownloadManager: false);
      if (id != null) {
        installUpdate();
      }
    } catch (err) {
      LogUtils.showLog("UpdateDialog-androidUpgrade-err=$err");

      if (err
          .toString()
          .contains("Read/Write External Storage permission not granted")) {
        ToastUtils.showToast("请在设置中为\"菲常go驾驶舱\"开启存储权限", isLong: true);

        //权限获取失败时回调
        callBack();
      }
    } finally {}
  }

  Future<void> installUpdate() async {
    final status = await RUpgrade.getDownloadStatus(id!);

    if (status == DownloadStatus.STATUS_SUCCESSFUL) {
      bool? isSuccess = await RUpgrade.install(id!);

      if (isSuccess != null && isSuccess) {
        if (id != null) {
          await RUpgrade.cancel(id!);
        }
      }
    } else {}
  }

  Future<void> iosUpgrade() async {
    if (await canLaunchUrl(Uri.parse(data.apkUrl))) {
      // 设置为竖屏
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      await launchUrl(Uri.parse(data.apkUrl));
    }
  }

  void showUpdateDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return WillPopScope(
          child: StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
            if (Platform.isAndroid) {
              RUpgrade.stream.listen((DownloadInfo info) {
                LogUtils.showLog("showUpdateDialog-\n"
                    "id=${info.id}\n"
                    "max_length=${NumberFormatUtils.formatFileSize(info.maxLength!.toDouble())}\n"
                    "current_length=${NumberFormatUtils.formatFileSize(info.currentLength!.toDouble())}\n"
                    "percent=${info.percent}\n"
                    "planTime=${info.planTime!.toStringAsFixed(0)}\n"
                    "path=${info.path}\n"
                    "speed=${info.speed}KB/s\n"
                    "status=${info.status}");

                setState(() {
                  percent = info.percent! / 100;
                  percentStr = "${info.percent!}";
                  netInfo =
                      "本次更新${NumberFormatUtils.formatFileSize(info.maxLength!.toDouble())}，速度${NumberFormatUtils.formatNum(num: info.speed!, position: 2)}KB/s";

                  if (info.status == DownloadStatus.STATUS_SUCCESSFUL) {
                    isUpdating = false;
                    hintText = "立即安装";
                    LogUtils.showLog("下载完成-------- ");
                  }
                });

                LogUtils.showLog("showUpdateDialog-sta\n"
                    "percent=$percent\n"
                    "percentStr=$percentStr\n"
                    "netInfo=$netInfo");
              });
            }

            return Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Stack(
                  children: [
                    Container(
                      alignment: Alignment.center,
                      width: 500.w,
                      height: 500.w,
                      margin: EdgeInsets.only(
                        left: 65.w,
                        right: 65.w,
                        top: 70.w,
                      ),
                      padding: EdgeInsets.only(left: 40.w, right: 40.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(20.w)),
                        image: const DecorationImage(
                          image: AssetImage("assets/images/icon_update_bg.png"),
                          fit: BoxFit.fill,
                        ),
                      ),
                      child: Column(
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 60.w,
                          ),
                          Text(
                            isUpdating ? "正在下载" : "版本更新",
                            style: TextStyle(
                              fontSize: 32.sp,
                              color: const Color(0xFF00EEFF),
                              fontWeight: FontWeight.bold,
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.center,
                          ),
                          SizedBox(
                            height: 20.h,
                          ),
                          Text(
                            isUpdating ? "请稍候..." : "更新内容",
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 24.sp,
                              color: const Color(0xff8BD8DD),
                              decoration: TextDecoration.none,
                              fontWeight: FontWeight.normal,
                            ),
                            textAlign: TextAlign.start,
                          ),
                          Expanded(
                            child: Text(
                              data.upgradeTips,
                              softWrap: true,
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: const Color(0xff8BD8DD),
                                decoration: TextDecoration.none,
                                fontWeight: FontWeight.normal,
                              ),
                              textAlign: TextAlign.start,
                            ),
                          ),
                          //更新进度条
                          Visibility(
                            visible: isUpdating,
                            child: Container(
                              margin:
                                  EdgeInsets.fromLTRB(60.w, 24.w, 60.w, 24.w),
                              child: Column(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                      color: const Color(0xFF88A8CA),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(50.w)),
                                    ),
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(10.w)),
                                            child: LinearProgressIndicator(
                                              value: percent,
                                              backgroundColor:
                                                  const Color(0xFF88A8CA),
                                              valueColor:
                                                  const AlwaysStoppedAnimation<
                                                      Color>(Color(0xFF00EEFF)),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 10.w,
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        "$percentStr%",
                                        softWrap: true,
                                        style: TextStyle(
                                          fontSize: 20.sp,
                                          color: const Color(0xff00EEFF),
                                          decoration: TextDecoration.none,
                                          fontWeight: FontWeight.normal,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                      const Spacer(),
                                      Text(
                                        "$percentStr/100",
                                        softWrap: true,
                                        style: TextStyle(
                                          fontSize: 20.sp,
                                          color: const Color(0xff00EEFF),
                                          decoration: TextDecoration.none,
                                          fontWeight: FontWeight.normal,
                                        ),
                                        textAlign: TextAlign.start,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),

                          GestureDetector(
                            onTap: () {
                              if (Platform.isIOS) {
                                iosUpgrade();
                              } else {
                                if (!isUpdating) {
                                  setState(() {
                                    isUpdating = true;
                                    hintText = "版本升级中…";
                                  });
                                  androidUpgrade(callBack: () {
                                    setState(() {
                                      isUpdating = false;
                                      hintText = "权限获取失败";
                                    });
                                  });
                                }
                              }
                            },
                            child: Container(
                              padding: EdgeInsets.only(top: 18.w, bottom: 18.w),
                              margin: EdgeInsets.only(
                                left: 50.w,
                                right: 50.w,
                                bottom: 60.w,
                              ),
                              width: double.infinity,
                              alignment: Alignment.center,
                              decoration: const BoxDecoration(
                                // borderRadius:
                                //     BorderRadius.all(Radius.circular(20.w)),
                                image: DecorationImage(
                                  image: AssetImage(
                                      "assets/images/icon_update_btn.png"),
                                  fit: BoxFit.fill,
                                ),
                              ),
                              child: Text(
                                hintText,
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  decoration: TextDecoration.none,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            );
          }),
          onWillPop: () async {
            return Future.value(true);
          },
        );
      },
    );
  }
}
